package com.hrt.datasender.datadao.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.btcode.orm.executer.IORMExecuter;
import com.btcode.orm.model.ModelPageResult;
import com.hrt.datasender.datacollect.model.SerialProtocolModel;
import com.hrt.datasender.datacollect.serial.protocol.ISerialDataProtocol;
import com.hrt.datasender.datacollect.serial.protocol.SerialDataProtocolLoader;
import com.hrt.datasender.datadao.model.BcSerialModel;
import com.hrt.db.DBManager;

public final class BcSerialService {

    private static volatile BcSerialService instance;

    private BcSerialService() {

    }

    public static BcSerialService getInstance() {
        if (instance == null) {
            synchronized (BcSerialService.class) {
                if (instance == null) {
                    instance = new BcSerialService();
                }
            }
        }
        return instance;
    }

    public BcSerialModel create(BcSerialModel model) {
        IORMExecuter executer = DBManager.getORMExecuter();
        executer.create(model);
        return model;
    }

    public void update(BcSerialModel model) {
        IORMExecuter executer = DBManager.getORMExecuter();
        executer.update(model);
    }

    public void delete(String id) {
        BcSerialModel model = new BcSerialModel();
        model.setId(id);
        BcDeviceMonitorParamService.getInstance().deleteByDevice(id);
        DBManager.getORMExecuter().delete(model);
    }

    /**
     * 获取注册的串口
     * 
     * @return
     */
    public List<BcSerialModel> getSerials() {
        ModelPageResult mpr = DBManager.getORMExecuter().getModelList(BcSerialModel.class, null,null);
        List<BcSerialModel> models = mpr.getData();
        return models;
    }

    public List<SerialProtocolModel> getSerialProtocols()
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        List<SerialProtocolModel> models = new ArrayList<>();
        List<ISerialDataProtocol> protocols = SerialDataProtocolLoader.getInstance().getExistProtocol();

        for (ISerialDataProtocol protocol : protocols) {
            SerialProtocolModel model = new SerialProtocolModel();
            model.setId(protocol.getProtocolId());
            model.setName(protocol.getProtocolName());
            models.add(model);
        }
        return models;
    }
}